//
//  MCScrollPageView.m
//  MClient
//
//  Created by  崔玉国 on 10-9-26.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MCScrollPageView.h"

#define kPageControllerWidth	120.0
#define kPageControllerHeight	11.0

@interface MCScrollPageView (Private)

- (void)showPage:(int)page animated:(BOOL)animated;

@end

@implementation MCScrollPageView

- (void)initView
{
	// Initialization code
	self.backgroundColor = [UIColor clearColor];
	
	_scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
	_scrollView.scrollsToTop = NO;
	_scrollView.showsHorizontalScrollIndicator = NO;
	_scrollView.showsVerticalScrollIndicator = NO;
	_scrollView.scrollEnabled = YES;
	_scrollView.bounces = YES;
	_scrollView.delaysContentTouches = YES;
	_scrollView.canCancelContentTouches = YES;
	_scrollView.delegate = self;
	// pagingEnabled参数，保证每次滑动最多只滑动一屏
	_scrollView.pagingEnabled = YES;
	[self addSubview:_scrollView];
	
	CGRect controllerRect = CGRectMake(CGRectGetMidX(self.bounds)-(kPageControllerWidth/2)
									   , CGRectGetMaxY(self.bounds)-kPageControllerHeight-1
									   , kPageControllerWidth
									   , kPageControllerHeight);
	
	_slideBarImage = [[UIImageView alloc] initWithFrame:controllerRect];
	_slideBarImage.image = [UIImage imageNamed:@"pageSlidebar.png"];
	[self addSubview:_slideBarImage];
	
	controllerRect.origin.y -= 1.0;
	_controlPage = [[UIPageControl alloc] initWithFrame:controllerRect];
	_controlPage.hidesForSinglePage = YES;
	_controlPage.userInteractionEnabled = YES;
	[_controlPage addTarget:self action:@selector(pageChangeAction) forControlEvents:UIControlEventValueChanged];
	[self addSubview:_controlPage];
	
	_pagesArray = [[NSMutableArray alloc] init];
}

- (id)initWithFrame:(CGRect)frame {
	if (self == [super initWithFrame:frame]) {
		[self initView];
	}
	return self;
}

- (void)awakeFromNib
{
	// Initialization code
	[self initView];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void) viewAppear:(UIView*)viewShow
{
	for (UIView* view in _pagesArray) {
		if (viewShow == view) {
			view.hidden = NO;
		} else {
			view.hidden = YES;
		}
	}
}

// set pages with UIViewController array
- (void)setPages:(NSArray *)pagesArray
{
	for (UIViewController *controller in _pagesArray){
		[controller.clientView removeFromSuperview];
	}
	
	[_pagesArray setArray:pagesArray];
	
	_slideBarImage.hidden = ([pagesArray count] <= 1);
	
	// a page is the width of the scroll view
	_scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * [_pagesArray count]
								  , _scrollView.frame.size.height);
	
	
	// pages are created on demand
	// load the visible page
	// load the page on either side to avoid flashes when the user starts scrolling
	for (int i=0; i<[_pagesArray count]; i++) {
		// replace the placeholder if necessary
		UIView* view = [_pagesArray objectAtIndex:i];
		// add the controller's view to the scroll view
		if (nil != view) {
			CGRect frame = self.frame;
			frame.origin.x = frame.size.width * i;
			frame.origin.y = 0;
			view.frame = frame;
			
			[_scrollView addSubview:view];
		}
	}
	// inite pagecontrl
	_controlPage.numberOfPages = [_pagesArray count];
	_controlPage.currentPage = 0;
	
	[self showPage:_controlPage.currentPage animated:NO];
}

- (void)dealloc {
	
	[_slideBarImage release];
	[_controlPage release];
	//for (UIViewController* page in _pagesArray) {
	//	[page viewDidDisappear:NO];
	//}
	[_pagesArray release];
	[_scrollView release];
	
    [super dealloc];
}

- (UIView *)currentViewController
{
	return [_pagesArray objectAtIndex:_controlPage.currentPage];
}

- (void)viewWillAppear:(BOOL)animated
{
	//[[_pagesArray objectAtIndex:_controlPage.currentPage] viewWillAppear:animated];
	[self viewAppear:[self currentViewController]];
}

- (void)viewDidAppear:(BOOL)animated
{
	//[[_pagesArray objectAtIndex:_controlPage.currentPage] viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	//[[_pagesArray objectAtIndex:_controlPage.currentPage] viewWillDisappear:animated];
	for (UIView* page in _pagesArray) {
		page.hidden = YES;
	}
}

// 使用控件切换页面
- (void)pageChangeAction
{
    // update the scroll view to the appropriate page
    [self showPage:_controlPage.currentPage animated:YES];
    // Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
    _pageChangeFlag = YES;
}

- (void)willChangeToPage:(NSUInteger)page
{
	int oldPage = _controlPage.currentPage;
	if (page != oldPage) {
		//TTLOG(@"-----------Change to page: %d", page);
		_controlPage.currentPage = page;
		
		// 视图切换显示
		[self viewAppear:[_pagesArray objectAtIndex:page]];
		[[NSNotificationCenter defaultCenter] postNotificationName:@"PageViewTitle" object:[NSNumber numberWithInteger:page]];
	}
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
	//TTLOG(@"scrollViewDidScroll");
	//int pageTemp = floor((_scrollView.contentOffset.x - 320.0 / 2) / 320.0) + 1;
	//TTLOG(@"-----------[%d]scrollViewDidScroll to page: %d [contentOffset:%f]",(_pageChangeFlag)?0:1, pageTemp, _scrollView.contentOffset.x);
	
    // We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
    // which a scroll event generated from the user hitting the page control triggers updates from
    // the delegate method. We use a boolean to disable the delegate logic when the page control is used.
    // Switch the indicator when more than 50% of the previous/next page is visible
	if (_pageChangeFlag) {
        // do nothing - the scroll was initiated from the page control, not the user dragging
        return;
    }
	CGFloat pageWidth = _scrollView.frame.size.width;
	//TTLOG(@"scrollView.contentOffset.x:%f, pageWidth:%f", scrollView.contentOffset.x, pageWidth);
    int page = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	if (page >= 0 && page < _pagesArray.count) {
		//TTLOG(@"-----------scrollViewDidScroll to page: %d [contentOffset:%f, pageWidth:%f]", page, _scrollView.contentOffset.x, pageWidth);
		[self willChangeToPage:page];
	}
	
    // A possible optimization would be to unload the views+controllers which are no longer visible
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	//TTLOG(@"scrollViewDidEndDragging decelerate[%d]", (int)decelerate);
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
	//TTLOG(@"scrollViewWillBeginDecelerating");
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	//TTLOG(@"scrollViewDidEndDecelerating");
	_pageChangeFlag = NO;

	[self viewAppear:[self currentViewController]];
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
	//TTLOG(@"scrollViewDidEndScrollingAnimation");
    _pageChangeFlag = NO;
	[self viewAppear:[self currentViewController]];
}

- (void)showPage:(int)page animated:(BOOL)animated
{
	//TTLOG(@"-----------show page: %d", page);
	CGRect frame = _scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [_scrollView scrollRectToVisible:frame animated:animated];
	
	[self viewAppear:[_pagesArray objectAtIndex:page]];
}



- (NSArray*)getPageArray
{
	return _pagesArray;
}
@end

